<template>
  <div class="login">
    <van-nav-bar
    :title="isLogin ? '面经登录' : '面经注册'"
    />
    <van-form ref="form" @submit="submit">
      <van-field v-model="account" name="用户名" required label="用户名" placeholder="请输入用户名" :rules="accountRules" />
      <van-field v-model="password" name="密码" required label="密码" placeholder="请输入密码" :rules="passwordRules" />
    
    <div class="button">
      <van-button size="large" native-type="submit" :color=" isLogin ? '#fa6d1d' : '#07c160'">{{ isLogin ? '提交' : '注册'}}</van-button>
    </div>
  </van-form>
    <div class="register" @click="changeMode">
      {{ isLogin ? '注册账号' : '已有账号,去登录'}}
    </div>
  </div>
</template>

<script>
import { loginApi, registerApi } from '@/api/login';
import { Toast } from 'vant';
export default {
  name: 'TtLogin',
  components: {},
  data () {
    return {
      account: '',
      password: '',
      isLogin: true,
      accountRules: [
        {
          required: true,
          message: '请填写用户名',
          trigger: 'onBlur'
        },
        {
          validator: (value) => {
            return value.length >= 5 && value.length <= 10;
          },
          message: '用户名长度必须在5到10个字符之间',
          trigger: 'onBlur'
        }
      ],
      passwordRules: [
        {
          required: true,
          message: '请填写密码',
          trigger: 'onBlur'
        },
        {
          validator: (value) => {
            return value.length >= 5 && value.length <= 20;
          },
          message: '密码长度必须在5到20个字符之间',
          trigger: 'onBlur'
        }
      ]
    }
  },
  methods: {
    changeMode () {
      this.isLogin = !this.isLogin;
      this.$refs.form.resetValidation(['用户名', '密码'])
      this.account = ''
      this.password = ''
    },
    async submit (values) {
      if (values) {
        if (this.isLogin) {
          // 当前通过submit校验，且处于登录状态
         const res = await loginApi(this.account, this.password)
        //  console.log(res)
        // 保存token
         localStorage.setItem('token', res.data.token)
         Toast.success('登录成功')
         this.account = ''
         this.password = ''
         this.$router.replace('/layout/article')
        } else {
          await registerApi(this.account, this.password)
          // console.log(res)
          Toast.success('注册成功')
          this.account = ''
          this.password = ''
          this.isLogin = !this.isLogin
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .button{
    margin-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
  }

  .register{
    margin-top: 12px;
    padding-right: 20px;
    text-align: right;
    font-size: 12px;
    color: #006699;
  }
</style>